from django.shortcuts import render
from django.views import View
from django.http import HttpResponseForbidden,JsonResponse,HttpResponse
import json
import django_redis
from apps.goods.models import SKU
from utils.response_code import RETCODE
from apps.carts.utils import Base
from meiduo_mall.settings.dev import logger
# 购物车的简单展示
class CartsSimpleView(View):
    def get(self,request):
        """
        1.判断是否登录
        2.根据情况获取购物车数据并且展示
        """
        user = request.user
        # 判断登录情况
        if user.is_authenticated:
            # 登录,从数据库获取数据返回给前端
            redis_ob = django_redis.get_redis_connection("carts")
            redis_dict = redis_ob.hgetall(user.id)
            cart_skus = []
            # 遍历redis
            for data in redis_dict.items():
                sku = SKU.objects.get(id=int(data[0].decode()))
                cart_skus.append({
                    "id" : sku.id,
                    "name" : sku.name,
                    "count" : json.loads(data[1].decode())["count"],
                    "default_image_url" : sku.default_image.url
                })
        else:
            # 从cookie获取到carts的值
            # 判断值carts是否存在,取值,返回给前端
            cookie_ob = request.COOKIES.get("carts")
            if cookie_ob :
                cookie_dict = Base().unbsecret(cookie_ob)
            else:
                cookie_dict = {}
            cart_skus = []
            for cookie in cookie_dict.items():
                sku = SKU.objects.get(id=int(cookie))
                cart_skus.append({
                    "id": sku.id,
                    "name": sku.name,
                    "count": json.loads(cookie[1])["count"],
                    "default_image_url": sku.default_image.url
                })
        return JsonResponse({
            "code" : RETCODE.OK,
            "errmsg" : "OK",
            "cart_skus":cart_skus

        })
# 购物车的全选
class CartsSelectView(View):
    def put(self,request):
        """
        1.接受参数,判断参数
        2.判断登录
        3.链接数据库,修改selected
        """
        # 1.接受参数
        selected = json.loads(request.body.decode()).get("selected")
        # 1.2.判断参数
        pass
        # 2.判断登录
        user = request.user
        if user.is_authenticated:
            #3.登录状态,连接数据库
            redis_ob = django_redis.get_redis_connection("carts")
            redis_all = redis_ob.hgetall(user.id)
            # 3.1 遍历redus_all修改selected
            for element in redis_all.items():
                sku_id = element[0].decode()
                sku_count = json.loads(element[1].decode())["count"]
                redis_ob.hset(user.id,sku_id,json.dumps({"count":sku_count,"selected":selected}))
            return JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
        else:
            """未登录,获取cookie"""
            cookie_ob = request.COOKIES.get("carts")
            if cookie_ob:
                cookie_dict = Base().unbsecret(cookie_ob)
            else:
                cookie_dict = {}
            for element in cookie_dict.items():
                sku_id = element[0]
                cookie_dict[sku_id]["selected"] = selected
            cookie_dict = Base().bsecret(cookie_dict)
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
            response.set_cookie("carts",cookie_dict,max_age=3600*24*14)
            return response
# 购物车的增删改查
class CartsView(View):
    # 删除购物车
    def delete(self,request):
        """
        根据ajax传入的sku_id删除数据.
        获取sku_id判断登录状态,判断sku_id是否存在
        """
        sku_id = json.loads(request.body.decode()).get("sku_id")
        # 判断登录
        user = request.user
        if user.is_authenticated:
            #登录,1.链接数据库,删除对应的sku_id属性
            redis_ob = django_redis.get_redis_connection("carts")
            redis_ob.hdel(user.id,sku_id)
            return JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
        else :
            #未登录,获取cookie,删除对应的cookie
            cookie_ob = request.COOKIES.get("carts")
            if cookie_ob:
                cookie_dict = Base().unbsecret(cookie_ob)
            else:
                cookie_dict = {}
            del cookie_dict[sku_id]
            cookie_dict = Base().bsecret(cookie_dict)
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
            response.set_cookie("carts",cookie_dict,max_age=3600*24*14)
            return response
    # 修改购物车
    def put(self,request):
        """
        1.接受数据,判断格式
        2.判断登录
        3.重构count.
        4.返回前端格式
        """
        # 1.1 接受数据
        sku_id = json.loads(request.body.decode()).get("sku_id")
        count = json.loads(request.body.decode()).get("count")
        selected = json.loads(request.body.decode()).get("selected",True)
        # 1.2 判断格式
        pass
        # 2.判断登录
        user = request.user
        # 已经登录
        if user.is_authenticated:
            # 2.1链接数据库
            redis_ob = django_redis.get_redis_connection("carts")
            # 2.2根据传入的sku_id找到需要修改的count
            # 2.3对count的值进行修改
            count = count
            redis_ob.hset(user.id, sku_id, json.dumps({"count": count, "selected": selected}))
            sku = SKU.objects.get(id=sku_id)
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),
                'amount': str(sku.price * count),
            }
            return JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', "cart_sku": cart_sku})

        else:
            #未登录
            #获取cookie
            cookie_ob = request.COOKIES.get("carts")
            #判断cookie_ob是否存在
            cookie_dict = {}
            if cookie_ob:
                # 存在解密
                cookie_dict = Base().unbsecret(cookie_ob)
            else:
                cookie_ob = {}
            cookie_dict[sku_id] = {"count":count,"selected":selected}
            cookie_dict = Base().bsecret(cookie_dict)
            sku = SKU.objects.get(id=sku_id)
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),
                'amount': str(sku.price * count),
            }
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', "cart_sku": cart_sku})
            response.set_cookie("carts",cookie_dict,max_age=3600*14*24)
            return response
    # 展示购物车
    def get(self,request):
        """
       1.判断是否登录
       2.如果登录从redis中获取数据返回给前端
       3.如果没登录从cookie中获取数据返回给前端
       """
        user = request.user
        # 判断是否登录
        if user.is_authenticated:
            #链接数据库,获取数据
            redis_ob = django_redis.get_redis_connection("carts")
            redis_dict = redis_ob.hgetall(user.id)
            sku_list = []
            for sku_key,sku_value in redis_dict.items():
                sku = SKU.objects.get(id = int(sku_key.decode()))
                sku_list.append({
                    "id" : sku.id,
                    "name" : sku.name,
                    "count" : json.loads(sku_value.decode())["count"],
                    "selected" : str(json.loads(sku_value.decode())["selected"]),
                    "default_image_url" : sku.default_image.url,
                    "price" : str(sku.price),
                    "amount" : str(sku.price * json.loads(sku_value.decode())["count"])
                })
            context = {
                'cart_skus': sku_list,
            }

            return render(request, 'cart.html', context)
        else:
            # 没登录,从cookie中获取数据
            cookie_ob = request.COOKIES.get("carts")
            if cookie_ob :
                sku_dict = Base().unbsecret(cookie_ob)
            else:
                sku_dict = {}
            sku_list = []
            print(sku_dict)
            for sku_key,sku_value in sku_dict.items():
                sku = SKU.objects.get(id = int(sku_key))
                sku_list.append({
                    "id" : sku.id,
                    "name" : sku.name,
                    "count" : sku_value["count"],
                    "selected" : str((sku_value)["selected"]),
                    "default_image_url" : sku.default_image.url,
                    "price" : str(sku.price),
                    "amount" : str(sku.price * sku_value["count"])
                })
            context = {
                'cart_skus': sku_list,
        }
            return render(request, 'cart.html', context)
    # 增加商品
    def post(self,request):
        # 判断客户是否登录决定存储购物车数据方式
        # 1.获取参数

        sku_id = json.loads(request.body.decode()).get("sku_id")
        count = json.loads(request.body.decode()).get("count")
        selected = json.loads(request.body.decode()).get("selected",True)
        # 2.判空判格式
        if not all([sku_id,count,selected]):
            return HttpResponseForbidden("不能为空")
        try :
            SKU.objects.get(id = sku_id)
        except :
            return HttpResponseForbidden("sku_id不存在")
        if not count >=0 and not type(count) is int:
            return HttpResponseForbidden("count格式错误")
        if not isinstance(selected,bool):
            return  HttpResponseForbidden('参数selected有误')
        # 判断是否登录
        user = request.user
        if user.is_authenticated:
        # 3.链接数据库
            redis_ob = django_redis.get_redis_connection("carts")
        # 3.1 读取全部的数据
            redis_alls = redis_ob.hgetall(user.id)
            # 3.2 判断是否redis_alls为空,如果为空则把数据存储到数据库
            if not redis_alls :
                redis_ob.hset(user.id,sku_id,json.dumps({"count":count,"selected":selected}))
            # 3.3 如果不为空则判断sku_id在不在数据库中
            # 如果在,sku_id增加,不在则创建新属性
            if str(sku_id).encode() in redis_alls:
                # 根据sku_id取出对应的商品
                sku_ob = json.loads(redis_ob.hget(user.id,sku_id).decode())
                count1 = sku_ob["count"]
                count1 += count
                redis_ob.hset(user.id, sku_id, json.dumps({"count": count1, "selected": selected}))
            else:
                redis_ob.hset(user.id, sku_id, json.dumps({"count": count, "selected": selected}))
            return JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})

        else:
            """
            没有登录的客户将数据保存在cookie中,
            1.判断cookie是否有carts这个id,没有则创建有则解密
            2.判断sku_id在不在cookie中,在的话累加,不在的话创建
            3.加密返回数据
            """
            cookie_ob = request.COOKIES.get("carts")
            if cookie_ob :
                cookie_dict = Base().unbsecret(cookie_ob)
            else:
                cookie_dict = {}
            if sku_id in cookie_dict:
                count1 = cookie_dict[sku_id]["count"]
                count1 += count
                cookie_dict[sku_id] = {"count":count1,"selected":selected}
            else:
                cookie_dict[sku_id] = {"count": count,"selected":selected}
            cookie_dict = Base().bsecret(cookie_dict)
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
            response.set_cookie("carts",cookie_dict,max_age=24*60*3600)
            return response









